package edu.fivegroup.mall.consumer;

import com.google.gson.Gson;
import edu.fivegroup.mall.cart.Cart;
import edu.fivegroup.mall.cart.CartDao;
import edu.fivegroup.mall.cart.CartDaoImpl;
import edu.fivegroup.mall.util.CommonResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@WebServlet("/consumer-login")
public class ConsumerLoginHandler extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String account = req.getParameter("username");
        String password = req.getParameter("password");


        ConsumerDao consumerDao = new ConsumerDaoImpl();
        Consumer consumer = consumerDao.login(account, password);
        if (consumer == null){
            resp.getWriter()
                    .write(new Gson()
                            .toJson(CommonResult.fail(400,"登录失败")));
        }

        CartDao cartDao = new CartDaoImpl();
        List<Cart> cartList = cartDao.getCartList(consumer.getId());
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("user",consumer);
        stringObjectHashMap.put("carts",cartList);


        resp.getWriter()
                .write(new Gson()
                        .toJson(CommonResult.success(stringObjectHashMap)));

    }
}
